let btn = document.querySelector('.btn')
let length_box = document.querySelector('.option .length')
let uppercase_box = document.querySelector('.option .uppercase')
let lowercase_box = document.querySelector('.option .lowercase')
let numbers_box = document.querySelector('.option .numbers')
let symbols_box = document.querySelector('.option .symbols')
let result_text_box = document.querySelector('.result_text')


let copy_btn = document.querySelector('.copy')

copy_btn.addEventListener("click", function () {
  let data = result_text_box.innerText

  if(navigator.clipboard){
    navigator.clipboard.writeText(data).then(res=>{
      alert('复制成功!')
    }).catch(err=>{
      console.log(err,"剪切板没有授权");
    })
  }else{
    let textarea = document.createElement('textarea')
    document.body.appendChild(textarea)
    textarea.value = data
    textarea.select()
    document.execCommand('copy')
    textarea.remove()
    alert('复制成功!')
  }

})

btn.addEventListener('click', function () {
  let length = +length_box.value
  let upper = uppercase_box.checked
  let lower = lowercase_box.checked
  let number = numbers_box.checked
  let symbol = symbols_box.checked

  result_text_box.innerText = getPassword(upper, lower, number, symbol, length)
})

let randomFun = {
  upper: getRandomUpper,
  lower: getRandomLower,
  number: getRandomNumer,
  symbol: getRandomSymbol
}


// 获取密码
function getPassword(upper, lower, number, symbol, length) {
  let types = [{ upper }, { lower }, { number }, { symbol }].filter(item => Object.values(item)[0])

  if (!types.length) {
    return ''
  }
  let pwd = ''


  for (let index = 0; index < length; index++) {
    let fun_index = Math.floor(Math.random() * types.length)
    let key = Object.keys(types[fun_index])[0]
    pwd += randomFun[key]()
  }
  return pwd
}

// 随机生成大写字母
function getRandomUpper() {
  return String.fromCharCode(Math.floor(Math.random() * 26) + 65)
}

// 随机生成小写字母
function getRandomLower() {
  return String.fromCharCode(Math.floor(Math.random() * 26) + 97)
}

// 随机生成数字
function getRandomNumer() {
  return String.fromCharCode(Math.floor(Math.random() * 10) + 48)
}

// 随机生成特殊字符
function getRandomSymbol() {
  let symbols = '`!@#$%^&*()-=~_+/*.[];,./{}:"|<>?'
  return symbols[Math.floor(Math.random() * symbols.length)]
}


// 重写copy方法

// document.addEventListener('copy', function (e) {
//   e.clipboardData.setData('text/plain', data)
//   e.preventDefault()
// })